import ServiceClient from '@/editor/common/js/workspace/service-client'
import { base64EncodeUnicode, base64DecodeUnicode } from '@/utils/utils';
import AppData from '@/editor/js/design-view/configuration-data/app-data'
import { generateId } from '@/utils/index'
import _ from 'lodash'
import store from '@/store';
export default class WorkspaceExplorer {

    constructor(config) {
        if (!_.has(config, 'application')) {
            log.error('Cannot init file browser. config: application not found.')
        }
        this.application = _.get(config, 'application');
        this._options = config;
        this.appData = {}
        this.workspaceServiceURL = _.get(this._options, 'application.config.services.workspace.endpoint');
        this._lastWidth = undefined;
        this._openedFolders = this.application.browserStorage.get("file-explorer:openedFolders") || [];
        this._items = [];
        this._latestExploreItem = undefined;
        this._serviceClient = new ServiceClient({ application: this.application });
    }


    openFolder = function (folderPath) {
        var self = this;
        this._openedFolders = [];
        if (self._latestExploreItem !== undefined) {
            self.removeExplorerItem(self._latestExploreItem);
        }
        this._openedFolders.push(folderPath);
        this.createExplorerItem(folderPath);
        this.persistState();
    };

    openFile = async function (filePath) {

        let file = await this._serviceClient.readFile(filePath);
        let currentTabForFile = this.application.tabController.getTabForFile(file);
        if (!_.isNil(currentTabForFile)) {
            this.application.tabController.setActiveTab(currentTabForFile);
            return;
        }
        let siddhiJson = await this._serviceClient.getDesignMXContent(file.content);
        let configurationJSON = base64DecodeUnicode(siddhiJson);
        if (configurationJSON != undefined && configurationJSON != '') {

            let tempObj = JSON.parse(configurationJSON)
            this.initialiseSiddhiAppData(tempObj)
            var jsonStr = { content: siddhiJson }
            var mxJson = await this._serviceClient.getDesignMXView(jsonStr);
            let option = { tabOptions: { file: file } }
            _.set(option, 'application', this.application);
            _.set(option, 'title', file.name.replace(".siddhi", ""));
            _.set(option, 'name', file.name.replace(".siddhi", ""));
            _.set(option, 'siddhiJson', siddhiJson);
            _.set(option, 'state', 'old');
            _.set(option, 'id', generateId());
            _.set(option, 'mxJson', mxJson);
            _.set(option, 'file', file);
            _.set(option, 'appData', this.appData);
            this.application.workspaceManager.createNewTab(option)
            // 添加到vuex
            store.commit('siddhi/setTab', option)
        }
    };
    initialiseSiddhiAppData(configurationJSON) {
        this.appData = new AppData();
        this.appData.setSiddhiAppName(configurationJSON.siddhiAppConfig.siddhiAppName);
        // set the app desc
        this.appData.setSiddhiAppDescription(configurationJSON.siddhiAppConfig.siddhiAppDescription);
        this.appData.setAppAnnotationList(configurationJSON.siddhiAppConfig.appAnnotationList)
        this.appData.setAppAnnotationObjectList(configurationJSON.siddhiAppConfig.appAnnotationListObjects)
        this.appData.setSourceList(configurationJSON.siddhiAppConfig.sourceList)
        this.appData.setSinkList(configurationJSON.siddhiAppConfig.sinkList)
        this.appData.setStreamList(configurationJSON.siddhiAppConfig.streamList)
        this.appData.setTableList(configurationJSON.siddhiAppConfig.tableList)
        this.appData.setTriggerList(configurationJSON.siddhiAppConfig.triggerList)
        this.appData.setWindowList(configurationJSON.siddhiAppConfig.windowList)
        this.appData.setAggregationList(configurationJSON.siddhiAppConfig.aggregationList)
        this.appData.setFunctionList(configurationJSON.siddhiAppConfig.functionList)
        this.appData.setWindowFilterProjectionQueryList(configurationJSON.siddhiAppConfig.queryLists.WINDOW_FILTER_PROJECTION)
        this.appData.setSequenceQueryList(configurationJSON.siddhiAppConfig.queryLists.SEQUENCE)
        this.appData.setJoinQueryList(configurationJSON.siddhiAppConfig.queryLists.JOIN)
        this.appData.setPatternQueryList(configurationJSON.siddhiAppConfig.queryLists.PATTERN)
        this.appData.setPartitionList(configurationJSON.siddhiAppConfig.partitionList)
    }
    reloadFile = function (siddhiFileName) {
        var file = this._serviceClient.readFile("workspace" + this.application.getPathSeperator() + siddhiFileName);
        var activeTab = this.application.tabController.getActiveTab();
        activeTab.getSiddhiFileEditor().getSourceView().setContent(file.getContent());
        activeTab.getFile()
            .setDirty(false)
            .save();
    };

    createExplorerItem = function (folderPath) {
        var opts = {};
        _.set(opts, "application", this.application);
        _.set(opts, "path", folderPath);
        _.set(opts, "index", this._items.length - 1);
        _.set(opts, "container", this._explorerContainer);
        var explorerItem = new ExplorerItem(opts);
        explorerItem.render();
        this.treeHeader = explorerItem.header;
        this.treeHeaderArrowHeadIcon = explorerItem.arrowHeadIcon;
        this._latestExploreItem = explorerItem;
        this._items.push(explorerItem);
    };
    removeExplorerItem = function (item) {
        item.remove();
        _.remove(this._items, function (itemEntry) {
            return _.isEqual(itemEntry.path, item.path);
        });
        _.remove(this._openedFolders, function (path) {
            return _.isEqual(path, item.path);
        });
        this.persistState();
    };

    persistState = function () {
        this.application.browserStorage.put("file-explorer:openedFolders", this._openedFolders);
    };

    isEmpty = function () {
        return _.isEmpty(this._openedFolders);
    };

    isActive = function () {
        return this._activateBtn.parent('li').hasClass('active');
    };

    render = function () {

    }
}

